package initDB.initH2;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import initDB.initH2.entity.Role;
import initDB.initH2.entity.User;
import initDB.initH2.entity.UserRole;

public class InitH2 extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/** The session factory. */
	private SessionFactory sessionFactory = SessionFactoryUtils.getSessionFactory();

	// <load-on-startup> 在web.xml中配置相关信息
	// <load-on-startup> 里面 填写 负数 或0 由容器随机加载
	// <load-on-startup> 里面写 大于等于0 越小 越优先 加载
	// <load-on-startup> 里面写相同的数字 由web容器决定顺序
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("TestLoad.doGet()");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("TestLoad.doPost()");
	}

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		System.out.println("TestLoad.service()");
		super.service(req, res);
	}

	@Override
	public void destroy() {
		System.out.println("TestLoad.destroy()");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void init() throws ServletException {

		Session session = this.sessionFactory.openSession();
		System.out.println("根据hibernate.cfg.xml创建session");
		System.out.println("数据初始化---------------------------"+session.toString());
		insert();
		String query = "FROM User";
		List<User> list = session.createQuery(query).list();
		System.out.println("用户数据---------------------------");
		for (User user : list) {
			System.out.println(user.getUserName());
		}
	}

	public void insert() throws ServletException {
		Session session = this.sessionFactory.openSession();
		Transaction tran=session.beginTransaction();
		
		//创建用户表
		session.save(new User("userid1","usercode1","admin",0,"665d0b91007f1d095c1f6aeec5107ecc",21,1,"admin@163.com","eed599089be792af8ff680f16834f9eb"));
		//创建角色表
		session.save(new Role("roleid1","rolecode1","管理员"));
		session.save(new Role("roleid2","rolecode2","总经理"));
		session.save(new Role("roleid3","rolecode3","部门经理"));
		//创建用户角色表
		session.save(new UserRole("userroleid1","userid1","roleid1"));
		
		tran.commit();
		session.close();
	}

	public static void main(String[] args) throws ServletException {
		new InitH2().insert();
		//new Init().init();
	}

}